'use strict';

//节省 云函数数量  
const db = uniCloud.database();
const uniID = require('uni-id');

const xl_user = db.collection('uni-id-users');
const xl_order = db.collection('xl_order');
const xl_cart = db.collection('xl_cart');
const xl_addr = db.collection('xl_addr');
const xl_goods = db.collection('xl_goods');
const xl_comment = db.collection('xl_comment');
const dbCmd = db.command;

const modules = {

	getAddrList: async (param) => {
		let {
			uid,
			token
		} = param;

		if (!uid) {
			return {
				code: 20001,
				msg: "请先登录"
			}
		}
		let res = await xl_addr.where({
			uid
		}).get();

		if (res.data) {
			return {
				code: 1,
				data: res.data
			}
		} else {
			return {
				code: 0,
				data: res.data
			}
		}


	},
	saveAddress: async (param) => {
		let {
			name,
			tel,
			addr_text,
			addr_code,
			detail,
			is_default,
			uid,
			addr_id,
			token
		} = param;


		if (!uid) {
			return {
				code: 20001,
				msg: "请先登录"
			}
		}


		if (is_default == 1) {

			await xl_addr.where({
				uid,
				is_default: 1
			}).update({
				is_default: 0
			});

		}
		// 有addr_id  算修改   没有算新增
		let res = {};
		if (!addr_id) {
			res = await xl_addr.add({
				name,
				tel,
				addr_text,
				addr_code,
				detail,
				is_default,
				uid
			});

		} else {

			res = await xl_addr.where({
				_id: addr_id
			}).update({
				name,
				tel,
				addr_text,
				addr_code,
				detail,
				is_default,
				uid
			});
		}


		return {
			code: 1,
			msg: addr_id ? '修改成功' : '添加成功',
			data: res.data
		};

	},
	async get_addr_detail(param) {

		let {
			uid,
			_id
		} = param;

		let res = await xl_addr.where({
			_id,
			uid
		}).get();

		return {
			code: 1,
			data: res.data
		}
	},
	del_addr: async (param) => {

		let {
			uid,
			_id
		} = param;

		let res = await xl_addr.doc(_id).remove();
		return {
			code: 1,
			msg: '删除成功',
			data: res
		};

	},
	get_default_addr: async (param) => {

		let {
			uid
		} = param;

		let res = await xl_addr.where({
			uid,
			is_default: 1
		}).get();

		return {
			code: 1,
			msg: "获取成功",
			data: res.data
		}


	},

	set_default_addr: async (param) => {

		let {
			uid,
			_id
		} = param;


		await xl_addr.where({
			uid,
			is_default: 1
		}).update({
			is_default: 0
		});

		let res = await xl_addr.doc(_id).update({
			is_default: 1
		});
		return {
			code: 1,
			msg: "设置成功",
			data: res.data
		};

	},
	async checkOrder(param) {

		let {
			uid,
			cart_id,
			token,
			type
		} = param;


		if (!uid) {
			return {
				code: 20001,
				msg: "请先登录"
			}
		}


		let base_money = 0;
		let goods = [];
		let all_amount = 0;
		let reduction = 0; //满减
		let shipping = 0; //运费
		cart_id = cart_id.split(',');


		let cartList = await xl_cart.where({
			uid,
			_id: dbCmd.in(cart_id)
		}).get();

		cartList.data.forEach(v => {
			goods.push(v);
			base_money += (v.price * 1000 * v.num) / 1000;
		})

		all_amount = base_money - reduction + shipping;

		let obj = {
			base_money,
			all_amount,
			goods,
			reduction,
			shipping
		};

		if (type == 'buy') {
			await xl_cart.where({
				_id: cart_id[0]
			}).update({
				status: 2
			})
		}

		return {
			code: 1,
			msg: '获取成功',
			data: obj
		};

	},
	async submitOrder(param) {

		let {
			uid,
			cart_id,
			desc,
			address,
			token
		} = param;




		let oDate = new Date();


		let order_sn = oDate.getFullYear() +
			(oDate.getMonth() + 1 < 10 ? ('0' + oDate.getMonth() + 1) : oDate.getMonth() + 1) +
			(oDate.getDate() < 10 ? '0' + oDate.getDate() : oDate.getDate()) + oDate.getTime();


		let base_money = 0;
		let goods = [];
		let all_amount = 0;
		let reduction = 0; //满减
		let shipping = 0; //运费
		cart_id = cart_id.split(',');


		let cartList = await xl_cart.where({
			uid,
			_id: dbCmd.in(cart_id)
		}).get();



		cartList.data.forEach(v => {
			goods.push(v);
			base_money += (v.price * 1000 * v.num) / 1000;
		})


		//base_money  商品金额合计
		//status 状态("1":"未支付",
		//  "2":"待发货",
		//  "3":"待收货",
		//  "5":"退款",
		//  "6":"待评价",
		//  "7":"已评价"
		//  "8":"已取消"
		//shipping  先定为0  包邮
		//reduction 满减
		//coupon  	红包
		//coupon_id  用的红包ID
		//all_amount   最后的金额
		//pay_type  支付方式 0  未选择  1 支付宝  2微信


		all_amount = base_money - reduction + shipping;
		let res = await xl_order.add({
			uid,
			order_sn,
			base_money,
			shipping: 0,
			goods,
			reduction,
			coupon: '',
			coupon_id: '',
			all_amount,
			pay_type: 0,
			remarks: '',
			status: 1,
			desc,
			address,
			add_time: oDate.getTime(),
			update_time: oDate.getTime(),
			pay_time: ''

		});

		if (res.id) {

			await xl_cart.where({
				uid,
				_id: dbCmd.in(cart_id)
			}).remove();
			return {
				code: 1,
				data: res.id
			}


		} else {

			return {
				code: 0,
				msg: "加入失败"
			}
		}



	},
	async getOrderList(param) {
		let {
			uid,
			status,
			skip,
			limit
		} = param;



		let _where = {
			"is_del": dbCmd.neq('1')
		};

		if (status == 0) {

			_where.status = dbCmd.in([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
		} else if (status == 7) {
			_where.status = dbCmd.in([6, 7])
		} else {
			_where.status = status - 0;
		}

		_where.uid = uid;


		let count = await xl_order.where(_where).count();
		let res = await xl_order.skip(skip - 0).limit(limit - 0).where(_where).orderBy("update_time", "desc").get();


		return {
			code: 1,
			data: res.data,
			count: count.total
		}

	},
	async get_all_order(param) {
		let {

		} = param;
		let res = await xl_order.where({}).get();
		return {
			code: 1,
			data: res.data
		}

	},
	async getOrderDetail(param) {

		let {
			uid,
			orderId,
			token
		} = param;

		if (!uid) {

			return {
				code: 20030,
				msg: '请登录'
			}
		}
		if (!orderId) {

			return {
				code: 20031,
				msg: '参数错误'
			}
		}

		let res = await xl_order.where({
			uid,
			_id: orderId
		}).get();
		return {
			data: res.data,
			code: 1
		};

	},
	//支付订单
	async payOrder(param) {

		let {
			pay_type,
			orderId,
			token
		} = param;




		let res = await xl_order.doc(orderId).update({
			pay_type,
			status: 2, //已支付
			update_time: new Date().getTime(),
			pay_time: new Date().getTime()
		});



		let goods_datas = await xl_order.doc(orderId).field({
			goods: true
		}).get();


		//减库存

		goods_datas = goods_datas.data[0].goods;
		for (let i = 0; i < goods_datas.length; i++) {

			let v = goods_datas[i];
			if (v.attr) {

				await xl_goods.where({
					_id: v.goods_id,
					'table.text': v.attr.split(',')
				}).update({
					'table.$.stock': dbCmd.inc(-v.num)
				})

			} else {

				await xl_goods.where({
					_id: v.goods_id
				}).update({
					stock: dbCmd.inc(-v.num)
				})


			}

		}


		return {
			code: 1,
			msg: "更新成功",
			data: res.data
		}
	},
	async cancel_order(param) {
		let {
			orderId,
			cancel_text
		} = param;
		let res = await xl_order.where({
			_id: orderId
		}).update({
			cancel_text,
			status: 8
		})
		return {
			code: 1,
			data: res
		}
	},
	async del_order(param) {
		let {
			orderId
		} = param;
		let res = await xl_order.where({
			_id: orderId
		}).update({
			is_del: 1
		})
		return {
			code: 1,
			data: res
		}
	},
	async send(param) {

		let {
			orderId,
			express_com,
			express_no
		} = param;

		let res = await xl_order.where({
			_id: orderId
		}).update({
			express_com,
			express_no,
			status: 3
		});

		return {
			code: 1,
			data: res
		}
	},
	async shouhuo(param) {

		let {
			orderId
		} = param;

		let res = await xl_order.where({
			_id: orderId
		}).update({
			status: 6
		});

		return {
			code: 1,
			data: res
		}
	},
	async saveOrderEvaluateAdd(param) {
		let {
			goods_id,
			content,
			score,
			images,
			uid,
			attr,
			orderId
		} = param;
		
		let userInfo = await xl_user.where({
			_id:uid
		}).field({username:true,avatar:true,nickname:true}).get();
		
		
	

		let res = await xl_comment.add({
			goods_id,
			content,
			score,
			images,
			uid,
			attr,
			orderId,
			add_time:new Date().getTime(),
			userInfo:userInfo.data[0]
		});
		
		await xl_order.where({
			_id:orderId
		}).update({
			status:7
		})
		
		return {
			
			code:1,
			msg:'提交成功',
			
		}
	}

}
//搞定参数
exports.main = async (event, context) => {
	//event为客户端上传的参数
	let param = {};
	let body = event.body;
	let module = event.path.slice(1);
	if (body) {
		//POST  
		if (event.isBase64Encoded) {
			body = Buffer.from(body)
		}
		param = JSON.parse(body)
	} else if (event.queryStringParameters) {
		param = event.queryStringParameters
	}
	let payload = await uniID.checkToken(param.token);

	if (payload.code && payload.code > 0) {
		return {
			op: 'token 检查失败',
			...payload
		}
	}

	if (!modules[module]) {
		//404
		return {
			"mpserverlessComposedResponse": true, // 使用阿里云返回集成响应是需要此字段为true
			"statusCode": 404,
		}

	}
	//参数传给下边的函数

	let result = await modules[module](param);
	result._token = payload.token;
	result.tokenExpired = payload.tokenExpired;
	return result


};
